package com.learn.databinding.workwithobservabledataobjects.bindlayoutwithlivedata

import androidx.databinding.Bindable
import androidx.databinding.Observable
import androidx.databinding.PropertyChangeRegistry
import androidx.databinding.library.baseAdapters.BR
import androidx.lifecycle.ViewModel

/**
 * 实现了[Observable]接口的ViewModel
 */
class ObservableViewModel : ViewModel(), Observable {
    private val callbacks = PropertyChangeRegistry()

    @get:Bindable
    var userName: String = ""
        set(value) {
            field = value
            //通知该属性的观察者进行更新
            notifyPropertyChanged(BR.userName)
        }

    /**
     * 注册监听
     */
    override fun addOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback?) {
        callbacks.add(callback)
    }

    /**
     * 移除监听
     */
    override fun removeOnPropertyChangedCallback(callback: Observable.OnPropertyChangedCallback?) {
        callbacks.remove(callback)
    }

    /**
     * 通知所有get方法被@Bindable注解修饰的属性变化
     */
    fun notifyChange() {
        callbacks.notifyCallbacks(this, 0, null)
    }

    /**
     * 通知指定的属性数据变化
     *
     * @param fieldId
     */
    fun notifyPropertyChanged(fieldId: Int) {
        callbacks.notifyChange(this, fieldId)
    }
}